# -*- coding:Utf-8 -*-
'''
Created on 25 nov. 2012

@author: fefoley
'''

import ConfigParser
from datetime import *
from codecs import decode, encode
from pyicl import Interval, IntervalSet, IntervalMap

from contents import Mail, Meeting, SentMeeting
import divers


def import_config(path_to_configfile):
    """
    Import the config file in a dictionary for latter use
    return config  typeof(dictionary)
    """
    parser = ConfigParser.ConfigParser()
    parser.read(path_to_configfile)
    return parser    


def import_mails(config):
    """    importer la liste des mails - décodage des lignes à faire par l'object Mail    """
    'read confil file to know where are the mail files'
    root_path = config.get('inputfiles','rootpath')
    file_paths = config.get('inputfiles','mails').split('\n')
    
    'read config file for setup variables : up/down time'
    setup = int(config.get('setuptime','mailstart'))
    setdown  = int(config.get('setuptime','mailend'))
    adh = int(config.get('setuptime','mailadherence'))
    
    'go through the files'
    lstmails = []
    for p in file_paths:
        f = open(root_path + p, 'r')
        f.readline() #ignore head lines
        for line in f:
            dline = decode(line, 'cp1252')    #depend on vba output
            mail = Mail(dline)                # lecture des lignes à faire par l'object
            mail.setsetup(setup, setdown, adh)
            lstmails.append(mail)   
        f.close()
    return lstmails

def import_sentmeetings(config):
    """    importer la liste des réunions - décodage des lignes à faire par l'object SentMeeting."""
    'read confil file to know where are the sentmeetings files'
    root_path = config.get('inputfiles','rootpath') 
    file_paths = config.get('inputfiles','meetings').split('\n')

    'read config file for setup variables : up/down time'
    setup = int(config.get('setuptime','sentmeetingstart'))
    setdown  = int(config.get('setuptime','sentmeetingend'))
    adh = int(config.get('setuptime','sentmeetingadherence'))
        
    'read config file for sender keywords'
    me = config.get('self','name')
    
    'go through the files'    
    lstsentmeetings = []
    for p in file_paths:
        f = open(root_path + p, 'r')
        f.readline() #ignore head lines   
        for line in f:
            dline = decode(line, 'cp1252')
            sentmeeting = SentMeeting(dline)
            ' check if I sent it before adding it to the list'         
            if me.lower() in sentmeeting.getsender().lower() :
                sentmeeting.setsetup(setup, setdown, adh)
                lstsentmeetings.append(sentmeeting) 
        f.close()
    return lstsentmeetings


def import_meetings(config):
    """    importer la liste des réunions - décodage des lignes à faire par l'object Meeting    """
    'read confil file to know where are the meetings files'
    root_path = config.get('inputfiles','rootpath')  
    file_paths = config.get('inputfiles','meetings').split('\n')

    'read config file for setup variables : up/down time'
    setup = int(config.get('setuptime','meetingstart'))
    setdown  = int(config.get('setuptime','meetingend'))
    adh = int(config.get('setuptime','meetingadherence'))    
    
    'go through the files'    
    lstmeetings = []
    for p in file_paths:
        f = open(root_path + p, 'r')
        f.readline() #ignore head lines   
        for line in f:
            dline = decode(line, 'cp1252')   
            meeting = Meeting(dline)                # lecture des lignes à faire par l'object
            meeting.setsetup(setup, setdown, adh)                     
            lstmeetings.append(meeting) 
        f.close()
    return lstmeetings


def import_holidays(config):
    """importer la liste des jours fériés
    import csv with holyday listing assuming the following structure: 
    Date(dd/mm/yyyy)  String(nom du jour férié)
    return list of (datetime.date, strNomJourFerie)
    """ 
    'read confil file to know where are the import_holidays files'
    root_path = config.get('inputfiles','rootpath')  
    file_paths = config.get('inputfiles','holidays').split('\n')

    'go through the files'          
    lstholidays = []
    for p in file_paths:    
        f = open(root_path + p, 'r')
        f.readline() #ignore head lines
        for line in f:
            dline = decode(line, 'cp1252') 
            linesplit = dline.rstrip('\n').rstrip('\r').split('\t')  # take off endofline - date+nomjourférié per line
            if len(linesplit) != 2:   # should be 2 fields
                raise Exception("format error for {0}".format(linesplit))  # could be some formatting errors
            else:
                lstholidays.append((datetime.strptime(linesplit[0], "%d/%m/%Y"), linesplit[1]))
        f.close()                   
    return lstholidays

def import_holidays2(config):
    """importer la liste des jours fériés
    import csv with holyday listing assuming the following structure: 
    Date(dd/mm/yyyy)  String(holiday name)
    return list IntervalMap of the holidays (date, name)
    """     
    
    'read confil file to know where are the import_holidays files'
    root_path = config.get('inputfiles','rootpath')  
    file_paths = config.get('inputfiles','holidays').split('\n')
    
    'go through the files'          
    holidays = IntervalMap()
    for p in file_paths:    
        f = open(root_path + p, 'r')
        f.readline() #ignore head lines
        for line in f:
            dline = decode(line, 'cp1252') 
            linesplit = dline.rstrip('\n').rstrip('\r').split('\t')  # take off endofline - date+nomjourférié per line
            if len(linesplit) != 2:   # should be 2 fields
                raise Exception("format error for {0}".format(linesplit))  # could be some formatting errors
            else:
                dateholiday = datetime.strptime(linesplit[0], "%d/%m/%Y").date()
                holidays = holidays.add(IntervalMap.Segment(Interval(dateholiday), divers.Str2sum(linesplit[1])))
        f.close()       
    return holidays

def import_daysoff2(config):
    """
    import csv with dayoff listing
    assuming the following structure: 
    FromDate(dd/mm/yyyy) ToIncludedDate(dd/mm/yyyy) TypeOfDayoff(string) NbOfDayoff(float) 
    return IntervalMap ([date, date], type)
    """
    'read confil file to know where are the import_daysoff files'
    root_path = config.get('inputfiles','rootpath')  
    file_paths = config.get('inputfiles','dayoffs').split('\n')
        
    dayoffs_map = IntervalMap()
    for p in file_paths:      
        f = open(root_path + p, 'r')
        f.readline() #ignore head lines
        for line in f:
            dline = decode(line, 'cp1252') 
            linesplit = dline.rstrip('\n').rstrip('\r').split('\t')  # take off endofline and split with TAB
            if len(linesplit) != 4:   # should be 4 fields
                raise Exception("format error for {0}".format(linesplit))  # could be some formatting errors
            else:
                strFromDate, strToDate, strType, _ = linesplit
                start_date = datetime.strptime(strFromDate, "%d/%m/%Y").date()
                end_date = datetime.strptime(strToDate, "%d/%m/%Y").date()
                dayoffs_map = dayoffs_map.add(IntervalMap.Segment(Interval(start_date, end_date), divers.Str2sum(strType)))
        f.close()
    return dayoffs_map    

def import_daysoff(config):
    """
    import csv with dayoff listing
    assuming the following structure: 
    FromDate(dd/mm/yyyy) ToIncludedDate(dd/mm/yyyy) TypeOfDayoff(string) NbOfDayoff(float) 
    return list of (date, date, type, nb)
    """
    'read confil file to know where are the import_daysoff files'
    root_path = config.get('inputfiles','rootpath')  
    file_paths = config.get('inputfiles','dayoffs').split('\n')
        
    lstdayoffs = []
    for p in file_paths:      
        f = open(root_path + p, 'r')
        f.readline() #ignore head lines
        for line in f:
            dline = decode(line, 'cp1252') 
            linesplit = dline.rstrip('\n').rstrip('\r').split('\t')  # take off endofline and split with TAB
            if len(linesplit) != 4:   # should be 4 fields
                raise Exception("format error for {0}".format(linesplit))  # could be some formatting errors
            else:
                strFromDate, strToDate, strType, strNb = linesplit
                lstdayoffs.append((datetime.strptime(strFromDate, "%d/%m/%Y"),
                                   datetime.strptime(strToDate, "%d/%m/%Y"), 
                                   strType, float(strNb)))
        f.close()
    return lstdayoffs    


def debug_output(debug_str, config):
    'read confil file to know where to output'
    root_path = config.get('outputfiles','rootpath')  
    file_path = config.get('outputfiles','debug')
    path = root_path + file_path
    f = open(path, 'w')
    f.write(debug_str)
    f.close
    
        
def output_timestrip(lst_timestrips, config): 
    """
    YYYY/MM/DD    tsStart    tsEnd    encoded_Label OpenHours  ClosedHours
    """     
    'read confil file to know where to output'
    root_path = config.get('outputfiles','rootpath')  
    file_path = config.get('outputfiles','timestrip')
    path = root_path + file_path
    f = open(path, 'w')
        
    for timestrips in lst_timestrips:
        for ts in timestrips:
            line = (ts.dtstart.strftime("%Y/%m/%d") +
                        '\t' + ts.dtstart.strftime("%H:%M") +
                        '\t' + ts.dtend.strftime("%H:%M") +
                        '\t' + ts.content.getlabel().replace('\t','\\utab').replace('\n','\\ueol') +
                        '\t' + str(divers.openhours(ts)) +
                        '\t' + str(divers.closedhours(ts)) +
                        '\r\n')
            wline = encode(line, 'cp1252')
            f.write(wline)
    
    f.close      

def output_alldayoffs(wddico, config):
    """
    output all off days (holidays, dayoffs, WE)
    YYYY/MM/DD    WE/Holiday/Dayoff    ALL/AM/PM    Name
    """
    'read confil file to know where to output'
    root_path = config.get('outputfiles','rootpath')  
    file_path = config.get('outputfiles','alldayoffs')
    path = root_path + file_path
    f = open(path, 'w')

    for _, year in wddico.items():
        for month in year:
            for wday in month:
                if wday: 
                    'let print it out  WE > Holyday > Dayoff'
                    
                    'WE'
                    if wday.isWE:
                        line = (wday.dtstart.strftime("%Y/%m/%d") +
                                '\t' + 'WE' +
                                '\t' + 'ALL' +
                                '\t' + wday.WEdico[wday.isWE] +
                                '\r\n')
                        wline = encode(line, 'cp1252')
                        f.write(wline)
                    
                    'holyday'
                    if wday.isholiday:
                        line = (wday.dtstart.strftime("%Y/%m/%d") +
                                '\t' + 'Holiday' +
                                '\t' + 'ALL' +
                                '\t' + wday.holiday +
                                '\r\n')
                        wline = encode(line, 'cp1252')
                        f.write(wline) 
                    
                    'day off'     
                    if wday.isdayoff:
                        'is it a full one or a half?'
                        if "-AM" in wday.dayoff:        # its a half day in the morning (provided it was encoded like it   # to be improved
                            partline = "AM"
                        elif "-PM" in wday.dayoff:      # its a half day in the afternoon (provided it was encoded like it   # to be improved
                            partline = "PM"
                        else:
                            partline ="ALL"             # its a full day (provided it was encoded like it   # to be improved
                        line = (wday.dtstart.strftime("%Y/%m/%d") +
                                '\t' + 'Dayoff' +
                                '\t' + partline +
                                '\t' + wday.dayoff +
                                '\r\n')
                        wline = encode(line, 'cp1252')
                        f.write(wline)                                             
                         
    f.close

    
def import_scope(config):
    """Function to read the scope : starting and ending day.   """
    str_start = config.get('workday','startday')
    str_end = config.get('workday','endday')
    start = datetime.strptime(str_start, "%d/%m/%Y").date()
    end = datetime.strptime(str_end, "%d/%m/%Y").date()

    return IntervalSet(Interval(start, end))


